package de.farbstreich.tozen2.client;

import java.io.BufferedReader;
import java.io.IOException;

import de.farbstreich.tozen2.common.TozenProtocolMessage;


/**
 * @author mo
 * receive messages from server and pass it trough the encoder.
 */
public class ClientSocketInputThread extends Thread {
	
	BufferedReader inputStream;
	ClientProtocolHandler clientProtocolHandler;
	boolean stopInput;
	private GameData gameData;
	
	public ClientSocketInputThread(BufferedReader inputStream, GameData gameData, ClientGUI gui) {
		super();
		this.inputStream = inputStream;
		this.gameData = gameData;
		stopInput = false;
		clientProtocolHandler = new ClientProtocolHandler(this.gameData);	
	}

	/**
	 * close all open socket connections
	 */
	public void close() {
		stopInput();
		try {
			inputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public synchronized void stopInput() {
		stopInput = true;
	}
	
	public void run() {
		String line;
		try {
			while (!stopInput) {
				if((line = inputStream.readLine()) == null)
					stopInput = true;
				else { doRequest(line.trim()); }
			}
		}
		catch(IOException e)
		{  System.out.println(e);  }
	}

	/**
	 * redirect input to protocol handler
	 * @param msg
	 */
	private void doRequest(String msg) {
		TozenProtocolMessage protocol = new TozenProtocolMessage(msg);
		System.out.println("Incoming Message: " + msg);
		clientProtocolHandler.getMethod(protocol);
	}

	
}
